<template>
  <div class="questionnaire-list">
    <div class="header">
      <h2>问卷列表</h2>
      <!-- 只有管理员可以看到新建按钮 -->
      <el-button v-if="userStore.isAdmin" type="primary" @click="handleAdd">新建问卷</el-button>
    </div>

    <el-table :data="questionnaires" style="width: 100%">
      <el-table-column prop="title" label="标题" />
      <el-table-column prop="description" label="描述" />
      <el-table-column label="状态">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template #default="scope">
          <!-- 管理员或创建者的操作 -->
          <template v-if="canManage(scope.row)">
            <!-- 未发布状态 -->
            <template v-if="scope.row.status === 0">
              <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" @click="handleDelete(scope.row)">删除</el-button>
              <el-button type="success" @click="handlePublish(scope.row)">发布</el-button>
            </template>
            
            <!-- 已发布状态 -->
            <template v-else-if="scope.row.status === 1">
              <el-button type="warning" @click="handleEnd(scope.row)">结束</el-button>
              <el-button type="primary" @click="handleStats(scope.row)">统计</el-button>
            </template>

            <!-- 已结束状态 -->
            <template v-else>
              <el-button type="primary" @click="handleStats(scope.row)">统计</el-button>
            </template>
          </template>

          <!-- 普通用户的操作 -->
          <template v-else>
            <!-- 已发布状态 -->
            <template v-if="scope.row.status === 1">
              <template v-if="hasSubmitted(scope.row.id)">
                <el-button type="info" @click="handleView(scope.row)">查看答卷</el-button>
              </template>
              <template v-else>
                <el-button type="primary" @click="handleFill(scope.row)">填写</el-button>
              </template>
            </template>
            <!-- 已结束状态 -->
            <template v-else-if="scope.row.status === 2">
              <template v-if="hasSubmitted(scope.row.id)">
                <el-button type="info" @click="handleView(scope.row)">查看答卷</el-button>
              </template>
            </template>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <Pagination
      v-model:page="currentPage"
      v-model:size="pageSize"
      :total="total"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { getList, remove, publish, end, getMySubmissions } from '@/api/questionnaire'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import Pagination from '@/components/Pagination.vue'

const userStore = useUserStore()
const router = useRouter()

const loading = ref(false)
const questionnaires = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const submittedQuestionnaires = ref(new Set())

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleString()
}

const loadData = async () => {
  loading.value = true
  try {
    const res = await getList({
      page: currentPage.value,
      size: pageSize.value
    })
    console.log('加载数据响应:', res) // 添加调试日志
    if (res.code === 200 && res.data) {
      questionnaires.value = res.data.records || []
      total.value = res.data.total || 0
      currentPage.value = res.data.current || 1
      pageSize.value = res.data.size || 10
    } else {
      ElMessage.error(res.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取问卷列表失败:', error)
    ElMessage.error('获取问卷列表失败')
  } finally {
    loading.value = false
  }
}

const handleAdd = () => {
  router.push('/questionnaire/detail')
}

const handleEdit = (row) => {
  router.push(`/questionnaire/detail/${row.id}`)
}

const handleSubmit = (row) => {
  router.push(`/questionnaire/submit/${row.id}`)
}

const handleStatistics = (row) => {
  router.push(`/questionnaire/statistics/${row.id}`)
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该问卷吗？', '提示', {
      type: 'warning'
    })
    const res = await remove(row.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      loadData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  loadData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadData()
}

// 加载用户已提交的问卷
const loadSubmissions = async () => {
  try {
    const res = await getMySubmissions()
    if (res.code === 200 && res.data) {
      submittedQuestionnaires.value = new Set(res.data.map(item => item.questionnaireId))
      console.log('已提交的问卷:', submittedQuestionnaires.value) // 添加调试日志
    }
  } catch (error) {
    console.error('获取提交记录失败:', error)
  }
}

// 判断问卷是否已提交
const hasSubmitted = (questionnaireId) => {
  console.log('检查问卷是否提交:', questionnaireId, submittedQuestionnaires.value.has(questionnaireId)) // 添加调试日志
  return submittedQuestionnaires.value.has(questionnaireId)
}

// 判断当前用户是否可以管理该问卷
const canManage = (questionnaire) => {
  const isCreator = questionnaire.creatorId && questionnaire.creatorId === userStore.user?.id
  const result = userStore.isAdmin || isCreator
  console.log('检查管理权限:', questionnaire.id, result) // 添加调试日志
  return result
}

const handlePublish = async (row) => {
  try {
    const res = await publish(row.id)
    if (res.code === 200) {
      ElMessage.success('发布成功')
      loadData()
    }
  } catch (error) {
    ElMessage.error('发布失败')
  }
}

const handleEnd = async (row) => {
  try {
    const res = await end(row.id)
    if (res.code === 200) {
      ElMessage.success('问卷已结束')
      loadData()
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const handleFill = (row) => {
  router.push(`/questionnaire/fill/${row.id}`)
}

const handleView = (row) => {
  router.push(`/questionnaire/view/${row.id}`)
}

const handleStats = (row) => {
  router.push(`/questionnaire/stats/${row.id}`)
}

const handlePageChange = (page) => {
  currentPage.value = page
  loadData()
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0: return '未发布'
    case 1: return '已发布'
    case 2: return '已结束'
    default: return '未知'
  }
}

// 获取状态对应的标签类型
const getStatusType = (status) => {
  switch (status) {
    case 0: return 'info'
    case 1: return 'success'
    case 2: return 'warning'
    default: return 'info'
  }
}

onMounted(async () => {
  await loadSubmissions() // 先加载提交记录
  await loadData() // 再加载问卷列表
})
</script>

<style scoped>
.questionnaire-list {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.el-button {
  margin-right: 10px;
}

.el-button:last-child {
  margin-right: 0;
}
</style> 